package com.fansl.allround.open.helper.mail;

import cn.hutool.core.util.RandomUtil;
import com.fansl.allround.open.api.entity.email.SendMailMessage;
import com.fansl.allround.open.api.entity.email.SendMailMessagePO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;

/**
 * @author fansl
 * @Description: 网易126邮箱发送邮件
 * @date 2019/10/10 13:38
 */
@Slf4j
@Component
public class RegisterMessageTemplateExecutor implements EmailMessageTemplateExecutor{
    @Resource
    private TemplateEngine templateEngine;
    /**
     * 创建消息模板
     *
     * @param sendMailMessagePO
     * @throws Exception
     */
    @Override
    public SendMailMessage createMessageTemplate(SendMailMessagePO sendMailMessagePO) throws Exception {
        SendMailMessage sendMailMessage = new SendMailMessage();
        //收件人
        sendMailMessage.setReceiver(sendMailMessagePO.getReceiver());
        //生成验证码
        String code = generateVerCode();
        //返回内容
        sendMailMessage.setReturnContent(code);
        //邮件正文
        sendMailMessage.setContent(createContent(code));
        //邮件标题
        sendMailMessage.setSubject(createSubject(sendMailMessagePO));
        return sendMailMessage;
    }

    private String createContent(String verifyCode){
        Context context = new Context();
        context.setVariable("verifyCode",verifyCode);
        return templateEngine.process("emailVerifyCode",context);
    }

    private String createSubject(SendMailMessagePO sendMailMessagePO){
        return sendMailMessagePO.getEmailMessageType().getDescription()+"验证码";
    }

    /**
     * 生成验证码
     * @return
     */
    private String generateVerCode(){
        return RandomUtil.randomNumbers(6);
    }
}
